<script setup lang="ts">
import { ref, onMounted, reactive, computed, watch, toRaw } from "vue";
import { getDeviceConfigApi, setDeviceConfigApi } from '@/api/configs/deviceConfig';
import { useI18n } from "vue-i18n";
import { IsBelongM1, IsBelongM2 } from "@/utils/appCommon/appCommonOptions/products";
import { DeviceModel } from "@/api/products/device";
import { getM2FirRange, getM2MeasureSpeedOptionOrStr } from "@/utils/appCommon/appCommonOptions/deviceConfig";
import { formatTimestampToDatetime } from "@/utils/appCommon/timeUtil";
import { ElMessageBox } from "element-plus";
import CopyDevices from './CopyDevices.vue';

const emit = defineEmits(['onsubmit']);

const props = defineProps({
  params: {
    type: Object,
    required: true
  },
  deviceNo: {
    type: String,
    required: true
  },
  deviceOptions: {
    type: Array,
    required: false,
    default: [],
  },
  forceRefresh: {
    type: Number,
    required: false,
    default: 0
  }
});

interface AeParamConfig {
  aeEet: number;
  aeHdt: number;
  aeHlt: number;
  aeThreshold: number;
  aeParaEnable: boolean;
  aeSystemTime: number;
  aeWaveEnable: boolean;
  aeMeasureMode: number;
  aeMeasureSpeed: number;
  aeMeasureState: boolean;
  aeMeasureTimes: number;
  aeMeasureLength: number;
  aeMeasureInterval: number;
  updatetime?: number;
}
const i18n = useI18n();


const current = ref(
  {
    configKey:"param",
    deviceNo: "",
    productId:0,
    productKey:"",
    updatedAt:0,
  }
)
const currentDeviceInfo = ref<DeviceModel>();
const state = reactive(
  {
    firActions:getM2FirRange()["500"],
    aeMeasureModeOptions: []
  }
)

// 复制设备配置
const copyDevices = ref<string[]>([]);
const form = ref<AeParamConfig>({
  aeEet: 0,
  aeHdt: 0,
  aeHlt: 0,
  aeThreshold: 0,
  aeParaEnable: false,
  aeSystemTime: 0,
  aeWaveEnable: false,
  aeMeasureMode: 0,
  aeMeasureSpeed: 0,
  aeMeasureState: false,
  aeMeasureTimes: 0,
  aeMeasureLength: 0,
  aeMeasureInterval: 0
});

watch(
  () => props,
  (newVal) => {
    current.value.updatedAt=0
    current.value.deviceNo = newVal.deviceNo;
    current.value.productId = newVal.params.productId;
    current.value.productKey = newVal.params.productKey;
    setTimeout(async ()=>{
      await loadConfig();
    })
  },{
    deep:true, immediate: true
  }
);

const ae_measure_point_count = computed(() => {
  // 采样点数计算方法
  // 采样时间：50us 采样速度200K
  // 下方显示
  // 采样点数：(200*1000/(1000*1000))*50
  if(form.value.aeMeasureLength && form.value.aeMeasureSpeed && form.value.aeMeasureLength>0){
    return  Number(form.value.aeMeasureSpeed) / 1000 * Number(form.value.aeMeasureLength)
  }else{
    return 0;
  }
})

const systemTime = computed(() => {
    if(!current.value.updatedAt || current.value.updatedAt==0){
      return "-";
    }
  return formatTimestampToDatetime(current.value.updatedAt)
})

const loading = ref(false);

// 加载配置
const loadConfig = async () => {
  try {
    loading.value = true;
    const res = await getDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
    });
    if (res.data?.configValue) {
      form.value = JSON.parse(res.data?.configValue);
      form.value.updatetime =  res.data?.updatedAt
      // 更新当前时间戳
      if (form.value.updatetime) {
        current.value.updatedAt = form.value.updatetime;
      }
    }
  } finally {
    loading.value = false;
    setAeMeasureModeOptions()
  }
};

// 保存配置
const saveConfig = async () => {
  try {
    loading.value = true;
    await setDeviceConfigApi({
      deviceNo: current.value.deviceNo,
      configKey: current.value.configKey,
      configValue: form.value,
      copyDevices: copyDevices.value
    });
  } finally {
    loading.value = false;
  }
};

// 修改保存配置方法，添加二次确认
const handleSaveConfig = async () => {
  try {
    // 显示确认对话框
    await ElMessageBox.confirm(
      i18n.t('buttons.tips.confirmSaveConfig')+"?",
      "",
      {
        confirmButtonText:i18n.t('buttons.confirm'),
        cancelButtonText:i18n.t('buttons.cancel'),
        type: 'warning'
      }
    )
    // 用户确认后执行保存操作
    await saveConfig();

    // 重新加载配置以更新时间戳
    setTimeout(async ()=>{
      await loadConfig();
    },2000)

  } catch (error) {
    // 用户取消或其他错误，不做任何操作
    console.log('保存已取消');
  }
};

onMounted(() => {

});

const m2SpeedOption = getM2MeasureSpeedOptionOrStr(null)

const changeFirActions = (e: any) => {
  const m2FirRange: object = getM2FirRange()
  if (m2FirRange.hasOwnProperty(e)){
    // @ts-ignore
    state.firActions = m2FirRange[e]
  }
}


const setAeMeasureModeOptions = ()=>{
  console.log("setAeMeasureModeOptions")
  if ( IsBelongM2(current.value.productKey)) {
    if(currentDeviceInfo.value && currentDeviceInfo.value.networkType==2){
      state.aeMeasureModeOptions = [
        {
          label: i18n.t("device.aeparam.LORA_CONTINUOUS_PASSIVE_MODE"),
          name: 6,
          disabled: false
        }
      ]
    }else{
      state.aeMeasureModeOptions = [{
        label: i18n.t("device.aeparam.CONTINUOUS_MEASURE"),
        name: 2,
        disabled: false
      }]
    }
  } else {
    if(currentDeviceInfo.value && currentDeviceInfo.value.networkType==2) {
      state.aeMeasureModeOptions = [{
        label: i18n.t("device.aeparam.LORA_ENVELOPE_ACTIVE_MODE"),
        name: 3,
        disabled: false
      },{
        label: i18n.t("device.aeparam.LORA_ENVELOPE_PASSIVE_MODE"),
        name: 4,
        disabled: false
      },{
        label: i18n.t("device.aeparam.LORA_CONTINUOUS_ACTIVE_MODE"),
        name: 5,
        disabled: false
      },{
        label: i18n.t("device.aeparam.LORA_CONTINUOUS_PASSIVE_MODE"),
        name: 6,
        disabled: false
      }]
    }else {
      state.aeMeasureModeOptions  = [{
        label: i18n.t("device.aeparam.ENVELOPE_MEASURE"),
        name: 1,
        disabled: false
      },
        {
          label: i18n.t("device.aeparam.CONTINUOUS_MEASURE"),
          name: 2,
          disabled: false
        },
        //7 定长
        {
          label: i18n.t("device.aeparam.FIX_LENGTH_MEASURE"),
          name: 7,
          disabled: false
        },
      ]
    }
  }
}

</script>

<template>
  <div class="ae-param-config">
    <el-form :model="form" >
      <el-form-item :label="i18n.t('device.deviceNo')" prop="deviceNo">
        <el-input v-model="current.deviceNo"  disabled />
      </el-form-item>

      <el-form-item :label="i18n.t('device.aeparam.THRESHOLD')+ '(dB)'" prop="aeThreshold" v-if="IsBelongM1(current.productKey)">
        <el-input-number v-model="form.aeThreshold" :min="20"  style="min-width:200px;"/>
      </el-form-item>

      <!--  m1 是输入框 -->
      <el-form-item :label="i18n.t('device.aeparam.MEASURE_SPEED')+ '(k/s)'" prop="aeMeasureSpeed" v-if="IsBelongM1(current.productKey)">
        <el-input-number v-model="form.aeMeasureSpeed" :min="1"  style="min-width:200px;"/>
      </el-form-item>

      <!--  m2 是单选框 -->
      <el-form-item :label="i18n.t('device.aeparam.MEASURE_SPEED')+ '(k/s)'" prop="aeMeasureSpeed" v-if="IsBelongM2(current.productKey)">
        <el-radio-group v-model="form.aeMeasureSpeed" @change="changeFirActions">
          <el-radio v-for="(o,index) in m2SpeedOption"  :key="index"   :label=o.value >
            {{ o.label }}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!--                ae_measure_mode：-->
      <!--                1. 包络方式-->
      <!--                2. 连续波模式-->
      <!--                3. lora包络主动模式-->
      <!--                4. lora包络被动模式-->
      <!--                5. lora连续波主动模式-->
      <!--                6. lora连续波被动模式-->
      <el-form-item :label="i18n.t('device.aeparam.MEASURE_MODE') "  prop="aeMeasureMode" >
        <el-radio-group v-model="form.aeMeasureMode">
          <el-radio v-for="(o,index) in state.aeMeasureModeOptions" :key="index"  :label="o.name" :disabled="o.disabled">
            {{o.label}}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <template v-if="[1,3,4].includes(form.aeMeasureMode)">
        <el-form-item :label=" i18n.t('device.aeparam.EET')+'(us)'" >
          <el-input-number v-model.number="form.aeEet"  style="min-width:200px;" ></el-input-number>
        </el-form-item>
        <el-form-item :label="i18n.t('device.aeparam.HDT')+'(us)'" >
          <el-input-number v-model.number="form.aeHdt"  style="min-width:200px;"></el-input-number>
        </el-form-item>
        <el-form-item :label="i18n.t('device.aeparam.HLT')+ '(us)'">
          <el-input-number v-model.number="form.aeHlt"  style="min-width:200px;"></el-input-number>
        </el-form-item>
      </template>

      <template v-if="[2,5,6].includes(form.aeMeasureMode)">
        <div style="display: flex;flex-direction: row;margin-left: 20px; justify-content: flex-start;">
          <h5 style="margin-left: 20px"> {{i18n.t('device.aeparam.MEASURE_POINT_COUNT')}}: {{ae_measure_point_count}} </h5>
        </div>
        <el-form-item :label="i18n.t('device.aeparam.MEASURE_LENGTH')+'(us)'" >
          <el-input-number v-model.number="form.aeMeasureLength"  :min="1"  style="min-width:200px;"></el-input-number>
        </el-form-item>
        <el-form-item :label="i18n.t('device.aeparam.MEASURE_TIMES') " >
          <el-input-number v-model.number="form.aeMeasureTimes" :min="1" style="min-width:200px;"></el-input-number>
        </el-form-item>
        <el-form-item :label="i18n.t('device.aeparam.MEASURE_INTERVAL') + '(us)'">
          <el-input-number v-model.number="form.aeMeasureInterval" :min="1" style="min-width:200px;"></el-input-number>
        </el-form-item>
      </template>

      <el-form-item :label=" i18n.t('device.aeparam.PROPERTY_ENABLE') " prop="aeParaEnable">
        <el-radio-group v-model="form.aeParaEnable">
          <el-radio :label="true" >{{i18n.t('buttons.yes')}}</el-radio>
          <el-radio :label="false" >{{i18n.t('buttons.no')}}</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item :label=" i18n.t('device.aeparam.WAVE_ENABLE') " prop="aeWaveEnable">
        <el-radio-group v-model="form.aeWaveEnable">
          <el-radio :label="true" >{{i18n.t('buttons.yes')}}</el-radio>
          <el-radio :label="false" >{{i18n.t('buttons.no')}}</el-radio>
        </el-radio-group>
      </el-form-item>

      <!-- 复制设备配置 -->
      <el-form-item :label="i18n.t('device.copyDevices.title')">
        <CopyDevices
          :device-no="current.deviceNo"
          v-model="copyDevices"
        />
      </el-form-item>

      <el-form-item :label=" i18n.t('device.aeparam.SYSTEM_TIME') " >
        <el-input v-model="systemTime" type="text" disabled></el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" :loading="loading" @click="handleSaveConfig" style="min-width: 150px;">
          {{i18n.t('buttons.submit')}}
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.ae-param-config {
  padding: 20px;
  overflow-x: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
}
</style>
